package Bui;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

public class XMLUtil2 {
    public static Object getBean() {
        try (InputStream inputStream = XMLUtil2.class.getClassLoader().getResourceAsStream("resources/config2.xml")) {
            if (inputStream == null) {
                throw new RuntimeException("config.xml not found in the classpath.");
            }

            // 创建DOM文档对象
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document doc = builder.parse(inputStream);
            doc.getDocumentElement().normalize();  // 规范化文档

            // 获取包含类名的节点列表
            NodeList nl = doc.getElementsByTagName("className");
            if (nl.getLength() == 0) {
                throw new RuntimeException("No className element found in config.xml.");
            }

            Node classNode = nl.item(0);
            if (classNode.getNodeType() != Node.ELEMENT_NODE) {
                throw new RuntimeException("The first className node is not an ELEMENT_NODE.");
            }

            Element classElement = (Element) classNode;
            String cName = classElement.getTextContent().trim();

            // 通过类名生成实例对象并将其返回
            Class<?> c = Class.forName(cName);
            return c.getDeclaredConstructor().newInstance();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}